#!/bin/bash
#
# go.sh
# Author: Andy Chu
#
# Shell snippets for Go language.

# NOTE:
#
# To get vim syntax highlighting, do:
#
# source ~/dev/go/misc/vim/syntax/go.vim

# TODO:
#
# See if you can store everything in one dir rather than using the package
# structure that the "go" tool likes (src/pkg/bin).  Would you have to invoke
# the compilers directly?  You probably won't get all the stdlib imports.

export GOROOT=~/dev/go
# installed into here
export GOPATH=$PWD/_build  # has to be absolute, weird

#export PATH=$PATH:~/dev/go/bin

banner() {
  echo
  echo --- $@ ---
  echo
}

go() {
  ~/dev/go/bin/go "$@"
}

# See http://code.google.com/p/goprotobuf/
get-protobuf() {
  go get code.google.com/p/goprotobuf/{proto,protoc-gen-go}
}

go-protoc() {
  # PLUGIN has to be in PATH
  # http://code.google.com/p/goprotobuf/source/browse/README
  mkdir go
  PATH=$PATH:~/dev/go/bin protoc --go_out go "$@"
  tree go
}

# Construct the weird go source tree
build() {
  mkdir -p _build/src/tnet
  mkdir -p _build/src/pgi
  cp tnet.go tnet_test.go _build/src/tnet
  cp pgi.go _build/src/pgi

  mkdir -p _build/bin
  cp app.go _build/bin
  cp testecho.go _build/bin
  cp tnet_demo.go _build/bin

  tree _build

  go install tnet
  go install pgi
}

run2() {
  local file=$1
  shift
  go run _build/bin/$file "$@"
}

run() {
  go run "$@"
}

# Run 'go test'
test() {
  go test "$@"
}


# Python tnet tool

readonly BASE_DIR=..
tnet() {
  PYTHONPATH=.. $BASE_DIR/bin/tnet.py "$@"
}

tnet-demo() {
  run2 tnet_demo.go "$@"
}


pgi() {
  # embed JSON in the TNET request
  local json='{"str": "x", "blah": 10}'

  banner Request

  # Echo request through pgi.go, output response as JSON
  tnet echo { .route .Echo  .request ."$json" } \
    | run2 app.go \
    | tnet to-json

  banner Ping

  tnet echo { .command .init  .format .tnet } \
    | run2 app.go \
    | tnet to-json
}

read-dict() {
  tnet echo { .command .init  .format .tnet } \
    | tnet-demo read-dict

  banner

  # Now do 2
  tnet echo { .a .b  .c .d } \
    | tnet-demo read-dict
}

stdin() {
  echo -e '3:foo,' | run2 tnet_demo.go stdin
}

read() {
  echo -e '3:foo,' | run2 tnet_demo.go read
  echo -e '5:xxzzy,' | run2 tnet_demo.go read
}

nested() {
  tnet echo { .command .init  .dict { .a .b } } | tnet-demo nested
}

dump() {
  tnet-demo dump
}

tnetb() {
  echo -e '3:foo,' | tnet-demo string

  echo -e '12:3:foo,3:bar,}' | tnet-demo read-dict
}

"$@"
